package com.jhhc.StormSurgeForecast.AstronomicalTide;



import com.alibaba.fastjson2.JSONObject;
import com.jhhc.FloodForecast.Sensor.Pojo.BDMS_ST_SENSOR_B;
import com.jhhc.FloodForecast.Sensor.Service.BDMS_ST_SENSOR_BService;
import com.jhhc.RHDB.Data.Pojo.Data;
import com.jhhc.RHDB.Data.Pojo.ST_TIDE_H;
import com.jhhc.RHDB.Data.Service.ST_TIDE_HService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.*;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.ChartEntity.ChartDataResult;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.DTO.StrmsrgHarInfo;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.DTO.TideForecastResult;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.DTO.Param;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Service.BDMS_CALCULATESCHEME_MService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Service.BDMS_FBC_RESULT_PService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Service.BDMS_ST_ASTROTD_FService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.*;
import com.jhhc.StormSurgeForecast.StormSurge.Service.BDMS_FBC_RESULT_AService;
import com.jhhc.utils.JsonResult;
import com.jhhc.utils.ToTimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LYQ
 */
@Api(value="TideController",tags={"潮位数据服务"})
@RequestMapping(value = "StormSurgeForecast/AstronomicalTide")
@RestController
@RequiredArgsConstructor
public class AstronomicalTideController {

    private final BDMS_ST_ASTROTD_FService bdms_st_astrotd_fService;

    private final GetSeaWallUitl getSeaWallUitl;

    private final BDMS_ST_SENSOR_BService bdms_st_sensor_bService;

    private final BDMS_FBC_RESULT_AService bdms_fbc_result_aService;

    private final ST_TIDE_HService st_tide_hService;

    private final GetHighAndLowTides getHIghAndLowTides;

    private final GetTideUitl getTideUitl;

    private final GetReportUitl getReportUitl;

    private final BDMS_FBC_RESULT_PService bdms_fbc_result_pService;

    private final BDMS_CALCULATESCHEME_MService bdms_calculatescheme_mService;

    //天文潮报表服务
    @ApiOperation("查询潮汐月报表数据")
    @RequestMapping(value = "Report/GetTidalMonthlyReport", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getTideHourData(@RequestBody TidalMonthlyParam tidalMonthlyParam){
        //return
        JsonResult jsonResult = new JsonResult();
        //构造日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 日期格式转换
        Calendar calendar = new GregorianCalendar();
        //
        List<String> stcds = new ArrayList<>();
        stcds.add(tidalMonthlyParam.getStationCode());
        //开始和结束日期
        String startTime=null;
        String endTime =null;
        //返回数据结构对象
        List<TidalMonthlyData> tidalMonthlyDatas = new ArrayList<>();
        TidalMonthly tidalMonthly = new TidalMonthly();
        //设置日期
        try {
            startTime = tidalMonthlyParam.getMonth()+"-01 00:00:00";
            Date end = format.parse(startTime);
            calendar.setTime(end);
            calendar.add(Calendar.MONTH,+1);
            endTime = format.format(calendar.getTime());

        }catch (Exception e){
            e.printStackTrace();
        }
        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectTide(tidalMonthlyParam.getStationCode()
                ,startTime,endTime,tidalMonthlyParam.getDepartmentId());
        //获取高低潮
        List<HighAndLowTides> highAndLowTides = getHIghAndLowTides.getHIghAndLowTides(bdmsStAstrotdFList);
//        for (HighAndLowTides highAndLowTide:highAndLowTides){
//            System.out.println(highAndLowTide);
//            if (highAndLowTide.getHighAndLowTidesData()!=null){
//                HighAndLowTidesDatas data = new HighAndLowTidesDatas();
//                highAndLowTide.getHighAndLowTidesData();
//            }
//
//        }
        tidalMonthly.setHighAndLowTides(highAndLowTides);
        tidalMonthly.setStationCode(tidalMonthlyParam.getStationCode());
        //获取数据后分组
        //根据小时分组
        Map<String, List<BDMS_ST_ASTROTD_F>> DayListGroup = bdmsStAstrotdFList.stream().collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getMonth2, Collectors.toList()));
        for (Map.Entry<String, List<BDMS_ST_ASTROTD_F>> List : DayListGroup.entrySet()) {
            TidalMonthlyData tidalMonthlyData = new TidalMonthlyData();
            List<Data> datas = new ArrayList<>();
            String re =List.getKey().substring(3,5);

            if (re.equals("00")) {
                tidalMonthlyData.setHour(List.getKey());
                for (int i = 0; i < List.getValue().size(); i++) {
                    if (List.getValue().get(i).getFtdz() != null) {
                        Data data = new Data( List.getValue().get(i).getDay(), List.getValue().get(i).getFtdz());
                        datas.add(data);
                    }
                }
                tidalMonthlyData.setDatas(datas);
                if (tidalMonthlyData.getDatas()!=null) {
                    tidalMonthlyData.getDatas().sort(Comparator.comparing(Data::getTM));
                }
                tidalMonthlyDatas.add(tidalMonthlyData);
            }
        }
        tidalMonthly.setTidalMonthlyDatas(tidalMonthlyDatas);
        if (tidalMonthlyDatas.size()>0) {
            tidalMonthly.getTidalMonthlyDatas().sort(Comparator.comparing(TidalMonthlyData::getHour));
        }else {
          List<BDMS_ST_ASTROTD_F> bdms_st_astrotd_f=  bdms_st_astrotd_fService.selectNewEstData(stcds);
            String dataMonth =bdms_st_astrotd_f.get(0).getYmdh().substring(0,7);
            tidalMonthly.setDataMonth(dataMonth);
        }

        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        jsonResult.setData(tidalMonthly);

        return jsonResult;
    }

    //查询潮汐整编表
    @ApiOperation("查询潮汐整编表")
    @RequestMapping(value = "Report/GetTideConsolidation", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetTideConsolidation(@RequestBody JSONObject jsonObject) {
        //return
        JsonResult jsonResult = new JsonResult();
        //返回集合对象
        List<TwcReport> twcReports = new ArrayList<>();
        //获取参数
        List<String> stationCodes = jsonObject.getList("stationCodes",String.class);
        String dateType = jsonObject.getString("dateType");
        String time = jsonObject.getString("time");
        Integer department = jsonObject.getInteger("departmentId");
        String unit = jsonObject.getString("unit");
        String startTime =null; String endTime =null;
        //日期格式转换对象
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();

        //获取取数码
        List<String> Stcds = new ArrayList<>();
        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectTwcByStcds(stationCodes);
        for (BDMS_ST_SENSOR_B bdms_st_sensor_b:bdms_st_sensor_bs){
            Stcds.add(bdms_st_sensor_b.getDatacode());
        }
        System.out.println(dateType);
        //创建查询日期
        try {
            if (dateType.equals("year")){
                startTime = time+"-01-01 00:00:00";
                calendar.setTime(format.parse(startTime));
                calendar.add(Calendar.YEAR,+1);
                calendar.add(Calendar.HOUR,-1);
                endTime =format.format(calendar.getTime());


            }else if (dateType.equals("month") ){
                startTime = time+"-01 00:00:00";
                calendar.setTime(format.parse(startTime));
                calendar.add(Calendar.MONTH,+1);
                calendar.add(Calendar.HOUR,-1);
                endTime =format.format(calendar.getTime());
            }
        }catch (Exception ignored){

        }
        //根据站码分组
        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList =bdms_st_astrotd_fService.selectFTDZ(Stcds,startTime,endTime,department);
        Map<String, List<BDMS_ST_ASTROTD_F>> StcdListGroup = bdmsStAstrotdFList.stream().collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getStcd, Collectors.toList()));
        for (Map.Entry<String, List<BDMS_ST_ASTROTD_F>> List : StcdListGroup.entrySet()) {
            TwcReport twcReport = new TwcReport();
            List<TwcReportData> twcReportDatas = new ArrayList<>();
            twcReport.setStationCode(List.getKey());
            //根据月份分组
            Map<String, List<BDMS_ST_ASTROTD_F>> MonthListGroup = List.getValue().stream().collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getDateTime, Collectors.toList()));
            for (Map.Entry<String, List<BDMS_ST_ASTROTD_F>> MonthList : MonthListGroup.entrySet()) {
                TwcReportData twcReportData = new TwcReportData();
                List<TidalMonthlyData> tidalMonthlyDataList = new ArrayList<>();
                //月份高低潮数据
                List<HighAndLowTidesDatas> highAndLowTidesDatas =new ArrayList<>();
                twcReportData.setMonth(MonthList.getKey().substring(5,7));
                Map<String, List<BDMS_ST_ASTROTD_F>> DayListGroup = MonthList.getValue().stream().collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getHour, Collectors.toList()));
                for (Map.Entry<String, List<BDMS_ST_ASTROTD_F>> DayList : DayListGroup.entrySet()) {
                    TidalMonthlyData tidalMonthlyData = new TidalMonthlyData();
                    java.util.List<Data> dataList = new ArrayList<>();
                    tidalMonthlyData.setHour(DayList.getKey());
                    for (BDMS_ST_ASTROTD_F bdms_st_astrotd_f:DayList.getValue()){


                        if (bdms_st_astrotd_f.getHltdmk()==0){
                            Data data = new Data();
                            data.setValue(bdms_st_astrotd_f.getFtdz());
                            data.setTM(bdms_st_astrotd_f.getYmdh().substring(0,11));
                            dataList.add(data);
                            tidalMonthlyData.setDatas(dataList);
                        }else {
                            HighAndLowTidesDatas highAndLowTidesDatas1 = new HighAndLowTidesDatas();
                            highAndLowTidesDatas1.setTm(bdms_st_astrotd_f.getYmdh());
                            highAndLowTidesDatas1.setValue(bdms_st_astrotd_f.getFtdz());
                            highAndLowTidesDatas1.setHltdmk(bdms_st_astrotd_f.getHltdmk());
                            highAndLowTidesDatas.add(highAndLowTidesDatas1);
                            highAndLowTidesDatas.sort(Comparator.comparing(HighAndLowTidesDatas::getTm));
                        }
                    }
                    tidalMonthlyDataList.add(tidalMonthlyData);

                    tidalMonthlyDataList.sort(Comparator.comparing(TidalMonthlyData::getHour));
                }
                twcReportData.setTideDatas(tidalMonthlyDataList);
                twcReportData.setTideHLDatas(highAndLowTidesDatas);
                twcReportDatas.add(twcReportData);
                twcReportDatas.sort(Comparator.comparing(TwcReportData::getMonth));

            }

            twcReport.setTwcDatas(twcReportDatas);
            twcReports.add(twcReport);
        }

        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        jsonResult.setData(twcReports);
        return  jsonResult;

    }


    //天文潮报表服务  GetMeasuredTideMonthReport
    @ApiOperation("查询实时水情数据")
    @RequestMapping(value = "Report/GetRealTimeHydrologic", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetRealTimeHydrologic(@RequestBody RealTimeHydrologicParam realTimeHydrologicParam){
        //return
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
//        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
//        DateTime time1 = DateTime.parse(realTimeHydrologicParam.getStartTime(), formatter);
//        DateTime time2 = DateTime.parse(realTimeHydrologicParam.getEndTime(), formatter);
//        if (time1.isBefore(time2)) {
//            jsonResult.setData(getTideUitl.getRealTimeHydrologic(realTimeHydrologicParam.getPid(),
//                    realTimeHydrologicParam.getStationCodes(),realTimeHydrologicParam.getStartTime(),
//                    realTimeHydrologicParam.getEndTime(),realTimeHydrologicParam.getDepartmentId()));
//        } else if (time1.isAfter(time2)) {
//            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
//        }

        List<RealTimeHydrologic> list =  getTideUitl.getRealTimeHydrologic(realTimeHydrologicParam.getProjectId(),
                realTimeHydrologicParam.getStationCodes(),realTimeHydrologicParam.getStartTime(),
                realTimeHydrologicParam.getEndTime(),realTimeHydrologicParam.getDepartmentId());
        if (list != null  && list.size()>0) {
            jsonResult.setData(list);
            jsonResult.setRemark("请求成功");
        }else {
            jsonResult.setRemark("未查询到此站点该时间段内的数据");
        }
        return jsonResult;

    }


    @Autowired
    private ToTimeUtil toTimeUtil;
    @ApiOperation("2222查询实时水情数据")
    @RequestMapping(value = "Report/GetRealTimeHydrologic2", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetRealTimeHydrologic2(@RequestBody RealTimeHydrologicParam realTimeHydrologicParam){
        //return
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        LocalDateTime dateTime1 = toTimeUtil.getDateTime(realTimeHydrologicParam.getStartTime());
        LocalDateTime dateTime2 = toTimeUtil.getDateTime(realTimeHydrologicParam.getEndTime());

        if (dateTime1.compareTo(dateTime2) <= 0) {
            List<ChartDataResult> chartDataResults = getTideUitl.getRealTimeHydrologic2(realTimeHydrologicParam.getProjectId(),
                    realTimeHydrologicParam.getStationCodes(),realTimeHydrologicParam.getStartTime(),
                    realTimeHydrologicParam.getEndTime(),realTimeHydrologicParam.getDepartmentId());

            if (chartDataResults.size()>0){
                jsonResult.setData(chartDataResults);
                jsonResult.setRemark("请求成功");
            }else {
                jsonResult.setRemark("未查询到此站点该时间段内的数据");
            }
        } else  {
            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
        }
//        if (dateTime1.compareTo(dateTime2) <= 0) {
//            List<ChartDataResult> chartDataResults = getTideUitl.getRealTimeHydrologic2(realTimeHydrologicParam.getProjectId(),
//                    realTimeHydrologicParam.getStationCodes(),realTimeHydrologicParam.getStartTime(),
//                    realTimeHydrologicParam.getEndTime(),realTimeHydrologicParam.getDepartmentId());
//
//            if (chartDataResults.size()>0){
//                jsonResult.setData(chartDataResults);
//                jsonResult.setRemark("请求成功");
//            }else {
//                jsonResult.setRemark("请检查参数，未查询到相关数据");
//            }
//        } else  {
//            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
//        }
        return jsonResult;

    }

    @ApiOperation("查询实测月报表数据")
    @RequestMapping(value = "Report/GetMeasuredTideMonthReport", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetMeasuredTideMonthReport(@RequestBody TidalMonthlyParam TidalMonthlyParam){
        //return
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        jsonResult.setData(getReportUitl.getMeasuredTideMonthReport(TidalMonthlyParam.getStationCode()
                ,TidalMonthlyParam.getMonth()));
        return jsonResult;
    }

    /**
     * 模型文件入库
     * param.getModelTp() 模型类型东中国海1，福建2，南中国海3，曙光4，智能模型5，混合模型6
     * 入BDMS_FBC_RESULT_P表
     */
    @ApiOperation("获取潮位站预报潮位结果")
    @RequestMapping(value = "Data/InsertModelData", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult insertModelData(@RequestBody Param param) {
        JsonResult jsonResult = new JsonResult();
        long startTime=System.currentTimeMillis();
        ModelFileRead modelFileRead = new ModelFileRead();
        if (param.getPath() != null && !"".equals(param.getPath()) && param.getCalSchemeId() != null
        && !"".equals(param.getCalSchemeId())) {
            String path;
            List<BDMS_FBC_RESULT_P> pList = null;
            switch (param.getModelTp()){
                case 1:
                    path = param.getPath() + File.separator + param.getCalSchemeId();
                    pList = modelFileRead.readtfupresuls(path,param.getCalSchemeId(),param.getDttp());
                    if (pList != null) {
                        int num = bdms_fbc_result_pService.batchInsert(pList);
                        jsonResult.setData("入库完成：" + num);
                    }
                    break;
                case 4:
                    path = param.getPath() + File.separator + param.getCalSchemeId();
                    pList = modelFileRead.insertReadFors61(path,param.getCalSchemeId(),param.getDttp());
                    if (pList != null) {
                        int num = bdms_fbc_result_pService.batchInsert(pList);
                        jsonResult.setData("入库完成：" + num);
                    }
                    break;
                case 5:
                    //增水
                    String path0 = param.getPath() + File.separator + param.getCalSchemeId() +
                            File.separator + "surge_output.dat";
                    //天文潮矫正
                    String path1 = param.getPath() + File.separator + param.getCalSchemeId() +
                            File.separator + "tide_output.dat";
                    //预报潮位
                    String path2 = param.getPath() + File.separator + param.getCalSchemeId() +
                            File.separator + "Stormtide_output.dat";
                    int num = 0;
                    for (int i = 0; i < 3; i++) {
                        if (i == 0) {
                            path = path0;
                        }else if (i == 1) {
                            path = path1;
                        }else {
                            path = path2;
                        }
                        pList = modelFileRead.modelJiaoZheng(path,param.getCalSchemeId(),i);
                        if (pList != null) {
                            int count = bdms_fbc_result_pService.batchInsert(pList);
                            num += count;
                        }
                    }
                    jsonResult.setData("入库完成：" + num);
                    break;
                case 2:
                case 3:
                case 6:
                default:
                    break;
            }


        }else {
            jsonResult.setData("传入的路径或计算方案id错误");
        }
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        long endTime=System.currentTimeMillis();
        float excTime=(float)(endTime-startTime)/1000;
        System.out.println("执行时间："+excTime+"s");
        return jsonResult;
    }

    //获取天文潮数据
    @ApiOperation("获取天文潮数据")
    @RequestMapping(value = "Data/GetForecastTide", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetForecastTide(@RequestBody JSONObject jsonObject)  {
        //return
        JsonResult jsonResult = new JsonResult();
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        List<String> stationCodes =  jsonObject.getList("stationCodes",String.class);
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
//        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
//        DateTime time1 = DateTime.parse(startTime, formatter);
//        DateTime time2 = DateTime.parse(endTime, formatter);
//        if (time1.isBefore(time2)) {
//            jsonResult.setData(getTideUitl.getForecastTide(stationCodes,startTime,endTime));
//        } else if (time1.isAfter(time2)) {
//            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
//        }
        jsonResult.setData(getTideUitl.getForecastTide(stationCodes,startTime,endTime));
        return jsonResult;
    }
    //获取精度评定
    @ApiOperation("获取精度评定")
    @RequestMapping(value = "Calculate/AccuracyEvaluation", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetAccuracyEvaluation(@RequestBody JSONObject jsonObject)  {
        //return
        JsonResult jsonResult = new JsonResult();


        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        Integer projectId = jsonObject.getInteger("projectId");
        boolean collateData  = jsonObject.getBoolean("collateData");
        //List<String> stationCodes =  jsonObject.getList("stationCodes",String.class);
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        jsonResult.setData(getTideUitl.getAccuracyEvaluation(projectId,startTime,endTime,collateData));
        return jsonResult;
    }


    //获取增水统计
    @ApiOperation("获取增水统计")
    @RequestMapping(value = "Data/GetAnstauStatistics", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetAnstauStatistics(@RequestBody RealTimeHydrologicParam realTimeHydrologicParam)  {
        //return
        JsonResult jsonResult = new JsonResult();
        String startTime = realTimeHydrologicParam.getStartTime();
        String endTime = realTimeHydrologicParam.getEndTime();
        int  departmentId= realTimeHydrologicParam.getDepartmentId();
        int pid =realTimeHydrologicParam.getProjectId();
        List<String> stationCodes =  realTimeHydrologicParam.getStationCodes();
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
//        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
//        DateTime time1 = DateTime.parse(startTime, formatter);
//        DateTime time2 = DateTime.parse(endTime, formatter);
//        if (time1.isBefore(time2)) {
//            jsonResult.setData(getTideUitl.getAnstauStatistics(stationCodes,startTime,endTime,pid,departmentId));
//
//        } else if (time1.isAfter(time2)) {
//            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
//        }
        jsonResult.setData(getTideUitl.getAnstauStatistics(stationCodes,startTime,endTime,pid,departmentId));
                return jsonResult;
    }
    //数据保存
    @ApiOperation("数据保存")
    @RequestMapping(value = "Calculate/DataPreservation", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult DataPreservation(@RequestBody JSONObject jsonObject) throws Exception {
        JsonResult jsonResult = new JsonResult();

        String res =getTideUitl.dataPreservation(jsonObject);
        jsonResult.setData(res);
        return jsonResult;
    }
    //调和分析
    @ApiOperation("调和分析计算")
    @RequestMapping(value = "Calculate/HarmonicAnalysis", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getHarmonicAnalysis(@RequestBody JSONObject jsonObject) throws Exception {
        JsonResult jsonResult = new JsonResult();
        int projectId = jsonObject.getInteger("projectId");
        String stationCode= jsonObject.getString("stationCode");
        String stationName = jsonObject.getString("stationName");
        String startTime= jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        TimeUtil timeUtil = new TimeUtil();
        String creationTime = timeUtil.currentTime();

       jsonResult =getTideUitl.GetHarmonicAnalysis(projectId,stationCode,stationName,startTime,endTime,creationTime);


        return jsonResult;
    }
    //数据补齐 dataPolishing
    @ApiOperation("数据自动补齐")
    @RequestMapping(value = "Calculate/AutomaticReplenishment", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult AutomaticReplenishment(@RequestBody JSONObject jsonObject) {
        JsonResult jsonResult = new JsonResult();
        int projectId = jsonObject.getInteger("projectId");
        String stationCode= jsonObject.getString("stationCode");
        Integer methodId = jsonObject.getInteger("methodId");
        String startTime= jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        boolean saveData = jsonObject.getBoolean("saveData");
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
//        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
//        DateTime time1 = DateTime.parse(startTime, formatter);
//        DateTime time2 = DateTime.parse(endTime, formatter);
//        if (time1.isBefore(time2)) {
//            try {
//                int res = getTideUitl.autoDataPolishing(projectId,stationCode,startTime,endTime,methodId,saveData);
//                if (res>0){
//                    jsonResult.setData(res);
//                }else {
//                    jsonResult.setData("数据补齐失败");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } else if (time1.isAfter(time2)) {
//            jsonResult.setRemark("开始时间大于结束时间，请更换参数值");
//        }
        int res = getTideUitl.autoDataPolishing(projectId,stationCode,startTime,endTime,methodId,saveData);
        if (res>0){
            jsonResult.setData(res);
            jsonResult.setRemark("数据补齐成功");
        }else {
            jsonResult.setData("数据补齐失败");
        }
        return jsonResult;

    }
    //获取调和分析常数
    @ApiOperation("获取调和分析常数")
    @RequestMapping(value = "Calculate/GetBlendingConstant", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetBlendingConstant(@RequestBody JSONObject jsonObject)  {
        JsonResult jsonResult = new JsonResult();
        String stationCode =jsonObject.getString("stationCode");
        Integer projectId =jsonObject.getInteger("projectId");
        List<StrmsrgHarInfo> bdms_fbc_strmsrg_harinfo= getTideUitl.getBlendingConstant(projectId,stationCode);
        if (bdms_fbc_strmsrg_harinfo!=null){
            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            jsonResult.setData(bdms_fbc_strmsrg_harinfo);
        }else {
            jsonResult.setStatusCode(500);
            jsonResult.setSucceeded(false);
            jsonResult.setData("获取失败");
        }
        return  jsonResult;

    }



    //天文潮预报计算
    @ApiOperation("天文潮预报计算")
    @RequestMapping(value = "Calculate/TideForecast", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult TideForecast(@RequestBody JSONObject jsonObject) throws Exception {
        JsonResult jsonResult = new JsonResult();
        String startTime= jsonObject.getString("startTime");
        String endTime =jsonObject.getString("endTime");
        List<String> paramSchemeIds = jsonObject.getList("paramSchemeIds", String.class);
        TideForecastResult tideForecastResult = getTideUitl.TideForecast(startTime,endTime,paramSchemeIds);
        if (tideForecastResult!=null){
            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            jsonResult.setData(tideForecastResult);
            jsonResult.setRemark("潮汐预报计算成功");
        }else {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(false);
            jsonResult.setData("计算失败");
            jsonResult.setRemark("潮汐预报计算失败");
        }



        return jsonResult;
    }

    //保存天文潮预报数据结构
    @ApiOperation("保存天文潮预报结果")
    @RequestMapping(value = "Calculate/saveTideData", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult saveTideData(@RequestBody JSONObject jsonObject) throws Exception {
        JsonResult jsonResult = new JsonResult();
        // List<String> paramSchemeIds = jsonObject.getList("paramSchemeIds", String.class);
        String userId =jsonObject.getString("userId");
        String paramSchemeId =jsonObject.getString("paramSchemeId");
        Integer projectId =jsonObject.getInteger("projectId");
        String stationCode = jsonObject.getString("stationCode");
        String res = getTideUitl.saveTideData(projectId,paramSchemeId,userId,stationCode);
        if ("保存成功".equals(res)){
            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            jsonResult.setData("潮汐预报数据保存成功");
            jsonResult.setRemark(res);
        }else {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(false);
            jsonResult.setData("潮汐预报数据保存失败");
            jsonResult.setRemark(res);
        }
        return jsonResult;
    }
    //获取调和分析实测数据 getHarmonicAnalysisTide
    @ApiOperation("获取整合数据")
    @RequestMapping(value = "Calculate/GetHarmonicAnalysisTide", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult GetHarmonicAnalysisTide(@RequestBody JSONObject jsonObject)  {
        JsonResult jsonResult = new JsonResult();
        String startTime= jsonObject.getString("startTime");
        String endTime =jsonObject.getString("endTime");
        String stationCode =jsonObject.getString("stationCode");
        Integer projectId =jsonObject.getInteger("projectId");
        try {

            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            jsonResult.setData( getTideUitl.GetHarmonicAnalysisTide(projectId,stationCode,startTime,endTime));


        } catch (Exception e) {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(true);
            jsonResult.setData( "");
            jsonResult.setData("请求异常");
            e.printStackTrace();
        }


        return jsonResult;
    }

    @ApiOperation("整编导入")
    @RequestMapping(value = "Data/InsertReorganize", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult insertReorganize(@RequestBody JSONObject jsonObject)  {
       JsonResult jsonResult = new JsonResult();
        List<ST_TIDE_H> st_tide_hList = new ArrayList<>();
        // 获取JSON中的字段值
        List<ST_TIDE_H> st_tide_hs = jsonObject.getList("RECORDS",ST_TIDE_H.class);
        int count = 0;
        int res =0;
        for (ST_TIDE_H sttideh : st_tide_hs) {
            ST_TIDE_H st_tide_h = new ST_TIDE_H();
            st_tide_h.setStcd(sttideh.getStcd());
            st_tide_h.setTm(sttideh.getTm());
            st_tide_h.setTdz(sttideh.getTdz());
            if (!"".equals(String.valueOf(sttideh.getAirp()))){
                st_tide_h.setAirp(sttideh.getAirp());
            }
            if (!"".equals(String.valueOf(sttideh.getTdchrcd()))){
                st_tide_h.setTdchrcd(sttideh.getTdchrcd());
            }
            if (!"".equals(String.valueOf(sttideh.getTdptn()))){
                st_tide_h.setTdptn(sttideh.getTdptn());
            }
            if (!"".equals(String.valueOf(sttideh.getHltdmk()))){
                st_tide_h.setHltdmk(sttideh.getHltdmk());
            }
            st_tide_hList.add(st_tide_h);
            // 处理每一行数据
            // 每隔250行执行批量入库
            count++;
            if (count == 250) {
                // 执行批量入库操作
                int re =   st_tide_hService.insertBatchOrUpdate(st_tide_hList);
                res += count+re;

                // 清空列表和计数器
                st_tide_hList.clear();
                count = 0;
            }
        }
        int res1=0;
        // 如果最后一批数据不足250行，也执行批量入库
        if (!st_tide_hList.isEmpty()) {
            // 执行批量入库操作
            res1 = st_tide_hService.insertBatchOrUpdate(st_tide_hList);
        }
        if (res+res1>0){
            jsonResult.setData("数量处理共计："+((res/2)+res1)+"条");
            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            return jsonResult;
        }
        return jsonResult;
    }

    //获取海堤天文潮数据
    @ApiOperation("获取海堤天文潮数据")
    @RequestMapping(value = "/Data/GetHourlyTwcTideBySeawall", method = RequestMethod.GET)
    public  JsonResult getTideDataBySeawall(@RequestParam  String startTime,@RequestParam String endTime  ,@RequestParam List<Integer> seawallId){
        JsonResult jsonResult = new JsonResult();


        //
        jsonResult.setData(getSeaWallUitl.getTideDataBySeawall(startTime,endTime,seawallId));
        jsonResult.setRemark("获取海堤天文潮数据成功");
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);


        return jsonResult;
    }

    @ApiOperation("方案删除")
    @RequestMapping(value = "/Data/DeleteCschemeId", method = RequestMethod.GET)
    public  JsonResult deleteCschemeId(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String projectId){
        JsonResult jsonResult = new JsonResult();
        List<String> cschemeIds = bdms_calculatescheme_mService.selectCschemeId(startTime,endTime,projectId);
        for (String cscheme : cschemeIds) {
            String cschemeId = cscheme.trim();
            //删除数据
            bdms_fbc_result_pService.deleteByCschemeId(cschemeId);
            //删除场数据
            bdms_fbc_result_aService.deleteByCschemeId(cschemeId);
            //删除方案
            bdms_calculatescheme_mService.deleteByCschemeId(cschemeId);
        }
        return jsonResult;
    }



}
